import { useAppStore } from '@/store';
import { IUserInfo } from '@/types/interface';

// 权限验证工具类
export class PermissionUtils {
  // 检查是否有指定权限
  static hasPermission(permissionCode: string): boolean {
    const store = useAppStore();
    const permissions = store.state.permissions || [];
    return permissions.includes(permissionCode);
  }

  // 检查是否有多个权限中的任意一个
  static hasAnyPermission(permissionCodes: string[]): boolean {
    return permissionCodes.some(code => this.hasPermission(code));
  }

  // 检查是否有所有权限
  static hasAllPermissions(permissionCodes: string[]): boolean {
    return permissionCodes.every(code => this.hasPermission(code));
  }

  // 检查用户角色
  static hasRole(roleCode: string): boolean {
    const store = useAppStore();
    const user = store.state.user as IUserInfo || {};
    const roles = user.roles || [];
    return roles.includes(roleCode);
  }

  // 检查是否有多个角色中的任意一个
  static hasAnyRole(roleCodes: string[]): boolean {
    return roleCodes.some(code => this.hasRole(code));
  }

  // 获取用户权限列表
  static getUserPermissions(): string[] {
    const store = useAppStore();
    return store.state.permissions || [];
  }

  // 获取用户角色列表
  static getUserRoles(): string[] {
    const store = useAppStore();
    const user = store.state.user as IUserInfo || {};
    return user.roles || [];
  }

  // 检查是否为超级管理员
  static isSuperAdmin(): boolean {
    const store = useAppStore();
    const user = store.state.user as IUserInfo || {};
    return user.superAdmin === 1;
  }

  // 获取用户信息
  static getUserInfo(): IUserInfo | null {
    const store = useAppStore();
    return store.state.user as IUserInfo || null;
  }

  // 检查菜单权限
  static hasMenuPermission(menuUrl: string): boolean {
    const store = useAppStore();
    const menus = store.state.menus || [];
    
    // 递归检查菜单权限
    const checkMenuPermission = (menuList: any[]): boolean => {
      for (const menu of menuList) {
        if (menu.url === menuUrl) {
          return true;
        }
        if (menu.children && menu.children.length > 0) {
          if (checkMenuPermission(menu.children)) {
            return true;
          }
        }
      }
      return false;
    };
    
    return checkMenuPermission(menus);
  }
}

// 权限指令
export const permission = {
  mounted(el: HTMLElement, binding: any) {
    const { value } = binding;
    if (value) {
      const hasPermission = PermissionUtils.hasPermission(value);
      if (!hasPermission) {
        el.style.display = 'none';
      }
    }
  }
};

// 角色指令
export const role = {
  mounted(el: HTMLElement, binding: any) {
    const { value } = binding;
    if (value) {
      const hasRole = PermissionUtils.hasRole(value);
      if (!hasRole) {
        el.style.display = 'none';
      }
    }
  }
};